package com.example.common.email;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;



@Slf4j
@Service
public class EmailServiceImpl {

    @Value("${spring.mail.username:hewenhui1024@163.com}")
    private String from;

    @Autowired
    private JavaMailSender emailSender;

    @Autowired
    private TemplateEngine templateEngine;
    public boolean sendVerificationEmail(String toEmail, String subject, String code, Long expirationTime) {
        try {
            // 1. 创建上下文并填充数据
            Context context = new Context();
            context.setVariable("email", toEmail);
            context.setVariable("code", code);
            context.setVariable("expirationTime", expirationTime);

            // 2. 渲染Thymeleaf模板
            String htmlContent = templateEngine.process("welcome", context);

            // 3. 发送邮件
            MimeMessage message = emailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from); // 发件人邮箱
            helper.setTo(toEmail);                  // 收件人邮箱
            helper.setSubject(subject);      // 邮件主题
            helper.setText(htmlContent, true);       // HTML内容

            emailSender.send(message);
            return true;
        } catch (MessagingException e) {
            log.error(e.getMessage(),e);
            return false;
//            throw new RuntimeException("邮件发送失败", e);
        }
    }

    public void sendSimpleEmail(String to, String subject, String text) {
        try {
            MimeMessage message = emailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from); // 发件人邮箱
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true); // 支持HTML内容

            emailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败", e);
        }
    }
}